package logic

import (
	"context"
	"fmt"
	"mycrm/models/mysqlinit"
	redisinit "mycrm/models/redislinit"
	"mycrm/pkg"

	"mycrm/mycrmrpc/internal/svc"
	"mycrm/mycrmrpc/mycrmrpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type RegisterLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewRegisterLogic(ctx context.Context, svcCtx *svc.ServiceContext) *RegisterLogic {
	return &RegisterLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *RegisterLogic) Register(in *mycrmrpc.RegisterRequest) (*mycrmrpc.RegisterResponse, error) {
	// todo: add your logic here and delete this line
	result, _ := redisinit.Client.Get("Captcha" + in.Account + "Register").Result()
	if in.Captcha != result {
		return nil, fmt.Errorf("图形验证码错误,请重新输入")
	}

	result1, _ := redisinit.Client.Get("SendSms" + in.Account + "Register").Result()
	if in.SendSms != result1 {
		return nil, fmt.Errorf("短信验证码错误,请重新输入")
	}
	var mycrm mysqlinit.User

	mysqlinit.DB.Debug().Where("account=?", in.Account).Find(&mycrm)

	if mycrm.ID != 0 {
		return nil, fmt.Errorf("用户账号已注册,请重新注册")
	}
	user := mysqlinit.User{

		Account:  in.Account,
		Password: pkg.Md5Password(in.Password),
	}
	mysqlinit.DB.Debug().Create(&user)
	return &mycrmrpc.RegisterResponse{
		Id: int64(user.ID),
	}, nil
}
